package com.bicon.botu.core.base.common.utils;

import com.bicon.botu.core.base.common.Enum.DeviceType;
import com.bicon.botu.core.base.common.entity.BaseResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * HTTP请求工具类
 * @author tandk
 * @date 2017/10/20 0020 下午 14:49
 */
public class HttpUtil {
    /**
     * 发送GET请求
     *
     * @param url     目的地址
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendGet(String url, String charset) throws IOException {
        String result = null;
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url     目的地址
     * @param map     请求参数
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendPost(String url, Map<String, String> map, String charset) throws IOException {
        String result = null;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator
                    .next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, charset);
        httpPost.setEntity(uefEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 获取完整url带参数
     */
    public static String getFullUrl(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String fullUrl = url;
        StringBuilder paramUrl = new StringBuilder();
        Map<String, String[]> map = request.getParameterMap();
        if (map != null) {
            if (!map.isEmpty()) {
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    paramUrl.append("&");
                    paramUrl.append(entry.getKey());
                    paramUrl.append("=");
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value + v;
                    }
                    paramUrl.append(value);
                }
                fullUrl = fullUrl + "?" + paramUrl.toString().replaceFirst("&", "");
            }
        }
        return fullUrl;
    }

    /**
     * 获取请求中参数
     */
    public static Map<String, String[]> getParamMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        if (map != null) {
            if (!map.isEmpty()) {
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value + v;
                    }
                }
            }
        }
        return map;
    }

    /**
     * 获取真实ip地址
     *
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        String unknown = "unknown";
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }


    /**
     * 输出结果
     *
     * @param response
     * @param result
     */
    public static void printFailMessage(HttpServletResponse response, BaseResult result) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(JsonUtil.toJson(result));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 获取请求来源设备类型
     *
     * @param request
     */
    public static String getSourceType(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        for (DeviceType type : DeviceType.ALL) {
            String name = type.getName();
            if ((userAgent.indexOf(name) != -1)) {
                return name;
            }
        }
        return "Unknown";
    }
}
